import React, { PureComponent } from "react"
import ReactDOM from "react-dom"
import { Polyline, Marker, Map } from "react-amap"
import { isNull } from '../../utils/helper';
export default class MiTrackMap extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {
			height: document.documentElement.clientHeight,
		}
	}

	componentWillReceiveProps(nextProps) {
		let { list: oldList } = this.props;
		let { list: newList } = nextProps;
		if(!_.isEqual(oldList,newList)){
			setTimeout(() => {
				this.map.setFitView()
			}, 500);
		}

	}

	componentWillMount() {
	}

	componentDidMount() {
		const hei = this.state.height - ReactDOM.findDOMNode(this.lv).getBoundingClientRect().top;
		this.setState({
			height: hei
		})
	}

	render() {

		let { lon_field = "lon", lat_field = "lat", final_marker_img, list } = this.props;
		if (isNull(final_marker_img)) {
			final_marker_img = "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png";
		}
		let { polyline_option } = this.props;
		polyline_option = {
			// draggable:false,
			showDir: true,  //显示方向(白色箭头)
			...polyline_option
		}
		let el = [];
		let polylinePath = [];
		list.map((item, key) => {
			if (!isNull(item[lon_field]) && !isNull(item[lat_field])) {
				polylinePath.push(
					{
						longitude: item[lon_field],
						latitude: item[lat_field]
					}
				)
			}
		})
		el.push(
			<Polyline
				{...polyline_option}
				style={{
					strokeWeight: 5,
					lineJoin: "round",
					lineCap: "round",
				}}
				path={polylinePath}
			/>
		)
		let final = list[list.length - 1];
		return (
			<div ref={el => this.lv = el} className="mi-listview" style={{ overflow: "hidden", height: this.state.height }} data-flex="dir:top box:first">
				<Map
					amapkey={AMAP_KEY}
					version={AMAP_VERSION}
					protocol="http:"
					animateEnable={true}
					// 必须配置plugins={["ToolBar"]},并且index.ejs中要引入xxxx amap.js xxx, new AMap.ToolBar()才不报错
					plugins={["ToolBar"]}
					events={{
						created: (map) => {
							this.map = map;
							try {
								let toolBar = new AMap.ToolBar();
								this.map.addControl(toolBar);
							}
							catch (e) {
								console.log("err:", e)
							}
						}
					}}
				>
					{/* 当前位置-最后一条数据 */}
					{
						final && <Marker
							render={() => {
								return (
									<img src={final_marker_img} style={{ height: "42px" }} />
								)
							}}
							offset={new AMap.Pixel(-21, -42)}
							position={{ longitude: final[lon_field], latitude: final[lat_field] }}
						>
						</Marker>
					}

					{/* 车辆轨迹 */}

					{el}
				</Map>
			</div>
		);
	}
}